import * as vscode from 'vscode';

// Vue 文件解析器
// 用于解析 Vue 文件中的模板部分
export class VueTemplateParser {
    // 检查文档是否是 Vue 文件
    static isVueDocument(document: vscode.TextDocument): boolean {
        return document.languageId === 'vue' || document.fileName.endsWith('.vue');
    }

    // 获取 Vue 文件中的模板内容
    static getTemplateContent(document: vscode.TextDocument): string | null {
        const text = document.getText();
        
        // 匹配 <template> 标签内容
        const templateMatch = text.match(/<template[^>]*>([\s\S]*)<\/template>/i);
        if (templateMatch && templateMatch[1]) {
            return templateMatch[1];
        }
        
        return null;
    }

    // 检查位置是否在 Vue 模板中
    static isInTemplateSection(document: vscode.TextDocument, position: vscode.Position): boolean {
        if (!this.isVueDocument(document)) {
            return false;
        }

        const text = document.getText();
        const offset = document.offsetAt(position);

        // 查找所有 <template> 标签
        const templateRegex = /<template[^>]*>|<\/template>/gi;
        let match;
        let inTemplate = false;
        let lastIndex = 0;

        while ((match = templateRegex.exec(text)) !== null) {
            const tag = match[0].toLowerCase();
            const tagStart = match.index;
            const tagEnd = tagStart + match[0].length;

            if (tag.startsWith('<template')) {
                // 找到 template 开始标签
                inTemplate = true;
                lastIndex = tagEnd;
            } else if (tag === '</template>') {
                // 找到 template 结束标签
                if (inTemplate && offset >= lastIndex && offset <= tagStart) {
                    return true;
                }
                inTemplate = false;
            }
        }

        return false;
    }

    // 获取 Vue 模板中的光标上下文
    static getTemplateContext(document: vscode.TextDocument, position: vscode.Position): {
        isInTemplate: boolean;
        isInTag: boolean;
        currentLineText: string;
        linePrefix: string;
    } {
        const isInTemplate = this.isInTemplateSection(document, position);
        const lineText = document.lineAt(position).text;
        const linePrefix = lineText.substring(0, position.character);

        return {
            isInTemplate,
            isInTag: this.isInsideHtmlTag(linePrefix),
            currentLineText: lineText,
            linePrefix: linePrefix
        };
    }

    // 检查是否在 HTML 标签内
    private static isInsideHtmlTag(linePrefix: string): boolean {
        // 检查是否在标签开始 < 之后
        const lastOpenBracket = linePrefix.lastIndexOf('<');
        const lastCloseBracket = linePrefix.lastIndexOf('>');
        
        return lastOpenBracket > lastCloseBracket;
    }

    // 提取 Vue 模板中的组件导入信息
    static extractComponentImports(document: vscode.TextDocument): Map<string, string> {
        const imports = new Map<string, string>();
        const text = document.getText();

        // 匹配 import 语句
        const importRegex = /import\s+({([^}]+)}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;
        let match;

        while ((match = importRegex.exec(text)) !== null) {
            const importPath = match[4];
            
            if (match[2]) {
                // 具名导入: import { Button, Input } from 'antd'
                const components = match[2].split(',').map(c => c.trim());
                components.forEach(comp => {
                    if (comp) imports.set(comp, importPath);
                });
            } else if (match[3]) {
                // 默认导入: import Button from 'antd'
                imports.set(match[3], importPath);
            }
        }

        // 匹配 components 选项
        const componentsRegex = /components\s*:\s*{([^}]+)}/s;
        const componentsMatch = text.match(componentsRegex);
        
        if (componentsMatch && componentsMatch[1]) {
            const componentsText = componentsMatch[1];
            const compRegex = /(\w+)\s*:\s*(\w+)/g;
            let compMatch;
            
            while ((compMatch = compRegex.exec(componentsText)) !== null) {
                const localName = compMatch[1];
                const importedName = compMatch[2];
                const importPath = imports.get(importedName);
                
                if (importPath) {
                    imports.set(localName, importPath);
                }
            }
        }

        return imports;
    }
}